<template>
  <div class="home-container">
    <el-card class="stats-card">
      <div class="stats-grid">
        <div class="stat-item" @click="handleRouter('rooms')">
          <div class="stat-label">总机房数</div>
          <div class="stat-value">{{ roomCount }}</div>
          <div class="stat-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
        </div>
        <div class="stat-item" @click="handleRouter('machines')">
          <div class="stat-label">总机器数</div>
          <div class="stat-value">{{ machineCount }}</div>
          <div class="stat-icon">
            <el-icon><Monitor /></el-icon>
          </div>
        </div>
        <div class="stat-item" @click="handleRouter('students')">
          <div class="stat-label">总学生数</div>
          <div class="stat-value">{{ studentCount }}</div>
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
        <div class="stat-item" @click="handleRouter('sessions')">
          <div class="stat-label">正在上机</div>
          <div class="stat-value">{{ activeSessionCount }}</div>
          <div class="stat-icon">
            <el-icon><Timer /></el-icon>
          </div>
        </div>
      </div>
    </el-card>

    <div class="charts-grid">
      <el-card class="chart-card">
        <template #header>
          <span>今日上机统计</span>
        </template>
        <div class="chart-container">
          <v-chart :option="dailyUsageOption" style="min-height: 400px" />
        </div>
      </el-card>
      <el-card class="chart-card">
        <template #header>
          <span>机房使用率</span>
        </template>
        <div class="chart-container">
          <v-chart :option="roomUsageOption" style="min-height: 400px" />
        </div>
      </el-card>
    </div>

    <el-card class="recent-sessions-card">
      <template #header>
        <span>最近上机记录</span>
        <el-button
          type="primary"
          @click="fetchDashboardData"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </template>
      <el-table
        :data="recentSessions"
        border
        v-loading="loading"
        empty-text="暂无上机记录"
      >
        <el-table-column
          prop="id_"
          label="会话ID"
          width="100"
        ></el-table-column>
        <el-table-column label="学生信息" min-width="150">
          <template #default="scope">
            <div>
              <div>ID: {{ scope.row.student_id }}</div>
              <div>姓名: {{ getStudentName(scope.row) }}</div>
              <div>学号: {{ getStudentNumber(scope.row) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="机器信息" min-width="150">
          <template #default="scope">
            <div>
              <div>编号: {{ getMachineNumber(scope.row) }}</div>
              <div>机房: {{ getRoomName(scope.row) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180">
          <template #default="scope">
            {{
              scope.row.end_time ? formatDateTime(scope.row.end_time) : "进行中"
            }}
          </template>
        </el-table-column>
        <el-table-column label="费用" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.total_cost) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getComputerRooms } from "../api/rooms";
import { getMachines } from "../api/machine";
import { getStudents } from "../api/students";
import { getActiveSessions, getHistorySessions } from "../api/sessions";
import { getStudentById } from "../api/students";
import { ElMessage } from "element-plus";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LineChart, PieChart } from "echarts/charts";
import { useRouter } from "vue-router";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart from "vue-echarts";
import {
  Refresh,
  OfficeBuilding,
  Monitor,
  User,
  Timer,
} from "@element-plus/icons-vue";
import { getElement } from "element-plus/es/utils/index.mjs";

use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// 统计数据
const roomCount = ref(0);
const machineCount = ref(0);
const studentCount = ref(0);
const activeSessionCount = ref(0);
const recentSessions = ref([]);
const loading = ref(false);
const router = useRouter();

// 缓存数据
const studentCache = ref(new Map());

// 图表配置
const dailyUsageOption = ref({
  title: {
    text: "今日上机统计",
  },
  xAxis: {
    type: "category",
    data: [
      "00:00",
      "03:00",
      "06:00",
      "09:00",
      "12:00",
      "15:00",
      "18:00",
      "21:00",
    ],
  },
  yAxis: {
    type: "value",
    name: "上机人数",
  },
  series: [
    {
      data: [3, 1, 2, 8, 15, 20, 12, 5],
      type: "line",
      smooth: true,
    },
  ],
});

const roomUsageOption = ref({
  title: {
    text: "机房使用率",
    left: "center",
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    top: "5%",
    left: "center",
  },
  series: [
    {
      name: "机房使用率",
      type: "pie",
      radius: ["40%", "70%"],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 2,
      },
      label: {
        show: false,
        position: "center",
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      labelLine: {
        show: false,
      },
      data: [],
    },
  ],
});

// 格式化金额
const formatCurrency = (value) => {
  if (value === undefined || value === null) return "¥0.00";
  return "¥" + parseFloat(value).toFixed(2);
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 获取学生姓名
const getStudentName = (session) => {
  return (
    session.student_name ||
    session.student?.name ||
    studentCache.value.get(session.student_id)?.name ||
    "未知"
  );
};

// 获取学生学号
const getStudentNumber = (session) => {
  return (
    session.student_number ||
    session.student?.student_id ||
    studentCache.value.get(session.student_id)?.student_id ||
    "未知"
  );
};

// 获取机器编号
const getMachineNumber = (session) => {
  return session.machine_number || session.machine?.machine_number || "未知";
};

// 获取机房名称
const getRoomName = (session) => {
  return session.room_name || session.machine?.room?.name || "未知";
};

// 丰富会话数据
const enrichSessionData = async (sessions) => {
  for (const session of sessions) {
    // 如果缺少学生信息，尝试获取
    if (!session.student_name && session.student_id) {
      try {
        const studentResponse = await getStudentById(session.student_id);
        studentCache.value.set(session.student_id, studentResponse.data);
      } catch (error) {
        console.warn(`获取学生 ${session.student_id} 信息失败:`, error);
      }
    }
  }
};

// 获取统计数据
const fetchDashboardData = async () => {
  loading.value = true;
  try {
    // 并行获取所有数据
    const [
      roomsResponse,
      machinesResponse,
      studentsResponse,
      activeSessionsResponse,
      historySessionsResponse,
    ] = await Promise.all([
      getComputerRooms(),
      getMachines(),
      getStudents(),
      getActiveSessions(),
      getHistorySessions(0, 10),
    ]);

    // 更新统计数据
    roomCount.value = roomsResponse.data.length;
    machineCount.value = machinesResponse.data.length;
    studentCount.value = studentsResponse.data.length;
    activeSessionCount.value = activeSessionsResponse.data.length;

    // 处理最近会话数据
    recentSessions.value = historySessionsResponse.data;
    console.log("最近会话原始数据:", recentSessions.value);

    // 丰富会话数据
    await enrichSessionData(recentSessions.value);

    // 更新机房使用率图表
    updateRoomUsageChart(
      roomsResponse.data,
      machinesResponse.data,
      activeSessionsResponse.data
    );
  } catch (error) {
    ElMessage.error(
      "获取仪表盘数据失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("Dashboard data error:", error);
  } finally {
    loading.value = false;
  }
};

// 更新机房使用率图表
const updateRoomUsageChart = (rooms, machines, activeSessions) => {
  // 按机房分组统计机器数量
  const roomMachineCount = {};
  rooms.forEach((room) => {
    roomMachineCount[room.id_] = machines.filter(
      (m) => m.room_id === room.id_
    ).length;
  });

  // 按机房分组统计活跃会话数量
  const roomActiveCount = {};
  activeSessions.forEach((session) => {
    const roomId = session.machine?.room_id || session.room_id;
    if (roomId) {
      roomActiveCount[roomId] = (roomActiveCount[roomId] || 0) + 1;
    }
  });

  // 准备图表数据
  const chartData = rooms.map((room) => {
    const total = roomMachineCount[room.id_] || 0;
    const active = roomActiveCount[room.id_] || 0;
    const usageRate = total > 0 ? Math.round((active / total) * 100) : 0;

    return {
      name: `${room.name} (${usageRate}%)`,
      value: active,
    };
  });

  roomUsageOption.value.series[0].data = chartData;
};

const handleRouter = (path) => {
  router.push(`/${path}`);
};

// 页面加载时获取数据
onMounted(() => {
  fetchDashboardData();

  // 每5分钟刷新一次数据
  setInterval(fetchDashboardData, 5 * 60 * 1000);
});
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  padding: 10px;
}

.stat-item {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  position: relative;
  box-shadow: none;
  transition: all 0.5s ease-in-out;
}

.stat-item:hover {
  cursor: pointer;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  transition: all 0.5s ease-in-out;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-icon {
  position: absolute;
  right: 16px;
  top: 16px;
  color: #409eff;
  font-size: 20px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  /* height: max-content; */
  min-height: fit-content;
}

.chart-container {
  width: 100%;
  /* height: 100%; */
  height: calc(100% - 40px);
}

.recent-sessions-card {
  margin-top: 20px;
}

:deep(.el-card__header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-table .cell) {
  word-break: break-word;
}
</style>
